package com.gxlevi.math.algorithm;

/**
 * 二分查找 非递归
 */
public class BinarySearch {
    public static void main(String[] args) {
        int arr[] = {1,5,9,11,15,19,22,45,666};
        System.out.println(find(arr, 5));
    }

    public static int find(int[] arr, int findVal) {
        int left, right, mid;
        left = 0;
        right = arr.length;
        while (left <= right) {
            mid = (left + right) / 2;
            if (arr[mid] > findVal) {
                right = mid - 1;
            } else if (arr[mid] < findVal) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
